package com.company.project.core;

import com.company.project.core.myException.NullException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 统一异常类
 * @author 徽州大都督
 * @date 2021/05/10
 */
@RestControllerAdvice
public class UnifiedException {

    /**
     * 统一异常
     * @param ex
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    public Result handleRE(RuntimeException ex){
        // String message = ex.getMessage ();
        return new Result(false,"系统错误，请联系管理员",null);
    }

    /**
     * 处理@Validated参数校验失败异常
     * @param ex 异常类
     * @return 响应x
     */
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        return Result.getFailure (ex.getBindingResult().getFieldError().getDefaultMessage());
    }

    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(NullException.class)
    public Result NullException(NullException ex){
        return Result.getFailure (ex.getMessage ());
    }
}
